﻿// <copyright file="RawXMLDAL.cs" company="The MITRE Corporation">
//    Copyright (c) 2010 The MITRE Corporation. All rights reserved.
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//    http://www.apache.org/licenses/LICENSE-2.0
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
// </copyright>

/////////////////////////////////////////////////////////////////////////////////////////////////
// RawXMLDAL.cs - Data Access Layer for Exposing Raw XML
// Project: IC.NETSOA- IC.NETDAL
//
// Language:    C#, .NET 4.0
// Platform:    Dell XPS m1530 Windows 7, VS 2010
// Author:      Don McGarry MITRE Rome
/////////////////////////////////////////////////////////////////////////////////////////////////

// Copyright (c) 2010 The MITRE Corporation. All rights reserved.
//
// NOTICE
// This software was produced for the U. S. Government
// under Contract No. FA8721-09-C-0001, and is
// subject to the Rights in Noncommercial Computer Software
// and Noncommercial Computer Software Documentation Clause
// (DFARS) 252.227-7014 (JUN 1995)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using ICNETServices;

namespace ICNETDAL
{
  /// <summary>
  /// This class contains various methods for pulling raw XML from the ICNETSOA databasee.
  /// </summary>
  public static class RawXMLDAL
  {
    /// <summary>
    /// Queries the ICNETSOA database for content objects and formats them into XML.
    /// </summary>
    /// <returns>A list of all the content objects in the database, formatted into XML. </returns>
    public static List<XElement> GetAllXML()
    {
      List<XElement> mylist = new List<XElement>();
      XElement temp;
      XNamespace xs = ICNETSOAConstants.ICNETbaseURI;
      EDXLSQLDataContext linQDB = new EDXLSQLDataContext(ICNETSOAConstants.ICNETConnectionString);
      var contentobjects = from emContent in linQDB.EmergencyMessageContents
                        join emContainer in linQDB.EmergencyMessageContainers on emContent.EmergencyMessageContainerId equals emContainer.Id
                        orderby emContainer.DateTimeSent
                        select emContent;
      foreach (EmergencyMessageContent contentobj in contentobjects)
      {
        string contentType = contentobj.Type.TrimEnd(' ');

        if (contentType.Equals("XML", StringComparison.InvariantCultureIgnoreCase))
        {
            XElement embeddedXml = (from xmlContent in linQDB.XMLContents
                                    where xmlContent.EmergencyMessageContentId == contentobj.Id
                                    select xmlContent.EmbeddedXMLContent).SingleOrDefault();
            if (embeddedXml != null)
            {
                mylist.Add(embeddedXml);
            }
        }
        else
        {
          if (!String.IsNullOrEmpty(contentobj.NonXMLContents[0].Uri))
          {
            temp = new XElement(xs + "NonXMLContent", contentobj.NonXMLContents[0].Uri);
          }
          else
          {
            temp = new XElement(xs + "NonXMLContent", ICNETSOAConstants.ICNETdatalinkToMIME + contentobj.DSCHash.ToString());
          }

          mylist.Add(temp);
        }
      }

      return mylist;
    }

    public static List<XElement> GetActiveXML()
    {
      List<XElement> mylist = new List<XElement>();
      XElement temp;
      XNamespace xs = ICNETSOAConstants.ICNETbaseURI;
      EDXLSQLDataContext linQDB = new EDXLSQLDataContext(ICNETSOAConstants.ICNETConnectionString);

      var exposureCaches = from p in linQDB.ExposureCaches
                      where p.ExpirationTime > DateTime.UtcNow
                      orderby p.PublishDate descending
                      select p;

      var contentobjects = from emContent in linQDB.EmergencyMessageContents
                           join expCache in exposureCaches on emContent.Id equals expCache.EmergencyMessageContentId
                           orderby expCache.LastUpdatedTime
                           select emContent;

      foreach (EmergencyMessageContent contentobj in contentobjects)
      {
        string contentType = contentobj.Type.TrimEnd(' ');

        if (contentType.Equals("XML", StringComparison.InvariantCultureIgnoreCase))
        {
          XElement embeddedXml = (from xmlContent in linQDB.XMLContents
                                  where xmlContent.EmergencyMessageContentId == contentobj.Id
                                  select xmlContent.EmbeddedXMLContent).SingleOrDefault();
          if (embeddedXml != null)
          {
            mylist.Add(embeddedXml);
          }
        }
        else
        {
          if (!String.IsNullOrEmpty(contentobj.NonXMLContents[0].Uri))
          {
            temp = new XElement(xs + "NonXMLContent", contentobj.NonXMLContents[0].Uri);
          }
          else
          {
            temp = new XElement(xs + "NonXMLContent", ICNETSOAConstants.ICNETdatalinkToMIME + contentobj.DSCHash.ToString());
          }

          mylist.Add(temp);
        }
      }

      return mylist;
    }

    public static List<XElement> GetExpiredXML()
    {
      List<XElement> mylist = new List<XElement>();
      XElement temp;
      XNamespace xs = ICNETSOAConstants.ICNETbaseURI;
      EDXLSQLDataContext linQDB = new EDXLSQLDataContext(ICNETSOAConstants.ICNETConnectionString);

      var exposureCaches = from p in linQDB.ExposureCaches
                           where p.ExpirationTime <= DateTime.UtcNow
                           orderby p.PublishDate descending
                           select p;

      var contentobjects = from emContent in linQDB.EmergencyMessageContents
                           join expCache in exposureCaches on emContent.Id equals expCache.EmergencyMessageContentId
                           orderby expCache.LastUpdatedTime
                           select emContent;

      foreach (EmergencyMessageContent contentobj in contentobjects)
      {
        string contentType = contentobj.Type.TrimEnd(' ');

        if (contentType.Equals("XML", StringComparison.InvariantCultureIgnoreCase))
        {
          XElement embeddedXml = (from xmlContent in linQDB.XMLContents
                                  where xmlContent.EmergencyMessageContentId == contentobj.Id
                                  select xmlContent.EmbeddedXMLContent).SingleOrDefault();
          if (embeddedXml != null)
          {
            mylist.Add(embeddedXml);
          }
        }
        else
        {
          if (!String.IsNullOrEmpty(contentobj.NonXMLContents[0].Uri))
          {
            temp = new XElement(xs + "NonXMLContent", contentobj.NonXMLContents[0].Uri);
          }
          else
          {
            temp = new XElement(xs + "NonXMLContent", ICNETSOAConstants.ICNETdatalinkToMIME + contentobj.DSCHash.ToString());
          }

          mylist.Add(temp);
        }
      }

      return mylist;
    }

    public static List<XElement> GetUpdatedXML(DateTime Since)
    {
      List<XElement> mylist = new List<XElement>();
      XElement temp;
      XNamespace xs = ICNETSOAConstants.ICNETbaseURI;
      EDXLSQLDataContext linQDB = new EDXLSQLDataContext(ICNETSOAConstants.ICNETConnectionString);

      var exposureCaches = from p in linQDB.ExposureCaches
                           where p.LastUpdatedTime >= Since.ToUniversalTime()
                           orderby p.PublishDate descending
                           select p;

      var contentobjects = from emContent in linQDB.EmergencyMessageContents
                           join expCache in exposureCaches on emContent.Id equals expCache.EmergencyMessageContentId
                           orderby expCache.LastUpdatedTime
                           select emContent;

      foreach (EmergencyMessageContent contentobj in contentobjects)
      {
        string contentType = contentobj.Type.TrimEnd(' ');

        if (contentType.Equals("XML", StringComparison.InvariantCultureIgnoreCase))
        {
          XElement embeddedXml = (from xmlContent in linQDB.XMLContents
                                  where xmlContent.EmergencyMessageContentId == contentobj.Id
                                  select xmlContent.EmbeddedXMLContent).SingleOrDefault();
          if (embeddedXml != null)
          {
            mylist.Add(embeddedXml);
          }
        }
        else
        {
          if (!String.IsNullOrEmpty(contentobj.NonXMLContents[0].Uri))
          {
            temp = new XElement(xs + "NonXMLContent", contentobj.NonXMLContents[0].Uri);
          }
          else
          {
            temp = new XElement(xs + "NonXMLContent", ICNETSOAConstants.ICNETdatalinkToMIME + contentobj.DSCHash.ToString());
          }

          mylist.Add(temp);
        }
      }

      return mylist;
    }
  }
}
